import { JcDecorator } from '../helper'
import { DictionaryArray, JcEnum } from '../models'
import type { IDictionary, ClassConstructor, EnumKey } from '../types'

/**
 * # 字典配置Key
 */
const DICTIONARY_KEY = 'Dictionary'

/**
 * # 标记属性的枚举字典
 * @param dictionary 字典数组
 * ---
 * ### 💡 如直接传入枚举类，该属性的类型则必须为对应枚举类`Key`的类型
 */
export function Dictionary<K extends EnumKey, E extends JcEnum<K>>(
  dictionary: DictionaryArray | ClassConstructor<E>
): Function {
  return (target: any, key: string) => {
    if (!(dictionary instanceof DictionaryArray)) {
      // 如果不是字典 转为字典
      dictionary = DictionaryArray.create((dictionary as any).toDictionary())
    }
    JcDecorator.setFieldConfig(target, key, DICTIONARY_KEY, dictionary)
  }
}

/**
 * # 获取属性枚举字典
 * @param target 目标类
 * @param key 属性名
 */
export function getDictionary<T extends IDictionary>(
  target: any,
  key: string
): DictionaryArray<T> | undefined {
  const config = JcDecorator.getFieldConfig(target, key, DICTIONARY_KEY)
  if (config) {
    return DictionaryArray.createCustom<T>(config)
  }
  return undefined
}
